//
//  ViewController.m
//  Test_WWDC2018_416
//
//  Created by lianglibao on 2021/8/12.
//  Copyright © 2021 梁立保. All rights reserved.
//

#import "ViewController.h"
#import "TwoViewController.h"
#import "CustomTableViewCell.h"
#import "TestB.h"
#import "TestA.h"


extern void _objc_autoreleasePoolPrint(void);
extern int _objc_rootRetainCount(id);

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray<NSIndexPath *> *displayIndexPaths;
@property (nonatomic, strong) NSDictionary *displayImagesMap;
@property (nonatomic, assign) UITableViewRowAnimation reloadAnimationType;

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	// 测试WWDC内存管理方法论
	[self setupSubviews];

	[self setupObserver];

	// 测试交换方法后, 调用时刻方法内self的指向.
	TestB *b = TestB.alloc.init;
	TestA *a = TestA.alloc.init;

	[a testA];
	[b testB];
}

- (void)viewWillAppear:(BOOL)animated {
	[self loadTableViewImages];
	[super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
	[self unloadTableViewImages];
	[super viewDidDisappear:animated];
}

// MARK: - setup
- (void)setupObserver {
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

- (void)setupSubviews {
	self.title = @"首页";
	[self.view addSubview:self.tableView];
}



// MARK: - UITableViewDeleagte & UITableViewDatasource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if ((indexPath.row % 2) == 0) {
		self.reloadAnimationType = UITableViewRowAnimationRight;
		[self.navigationController pushViewController:TwoViewController.alloc.init animated:YES];
	} else {
		self.reloadAnimationType = UITableViewRowAnimationBottom;
		TwoViewController *twoVC = TwoViewController.alloc.init;
		twoVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
		__weak typeof(self) weakSelf = self;
		twoVC.dismissBlock = ^{
			[weakSelf loadTableViewImages];
		};
		[self.navigationController presentViewController:twoVC animated:YES completion:^{
			[weakSelf unloadTableViewImages];
		}];
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:NSStringFromClass(self.class)];
	@autoreleasepool {
		NSString *cacheKey = [NSString stringWithFormat:@"%ld_%ld", indexPath.section, indexPath.row];
		id image = [self.displayImagesMap valueForKey:cacheKey];
		if (!image) {
			NSString *name = (indexPath.row % 2 == 0) ? @"test02.jpeg" : @"test03.jpeg";
			NSURL *url = [[NSBundle mainBundle] URLForResource:name withExtension:nil];
			NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe | NSDataReadingUncached error:nil];
			image = [UIImage imageWithData:data];
			// 对比使用两种读取Image API
//			image = [UIImage imageNamed:name];
		}

		if (!cell.hasTapGesture) {// 防止复用重复加tap手势.
			UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
																				  action:@selector(cellTapAction:)];
			[cell addGestureRecognizer:tap];
			cell.hasTapGesture = YES;
		}
		cell.imageView.image = image;
	}
	return cell;
}

// MARK: - action & private method
- (void)cellTapAction:(UITapGestureRecognizer *)tap {
	UITableViewCell *cell = (UITableViewCell *)tap.view;
	NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
	[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
}

- (void)loadTableViewImages {
	// 打开return,对比分析
	//	return;
	if (self.displayIndexPaths) {
		[self.tableView beginUpdates];
		[self.tableView reloadRowsAtIndexPaths:self.displayIndexPaths
							  withRowAnimation:self.reloadAnimationType];
		[self.tableView endUpdates];
		self.displayIndexPaths = nil;
		self.displayImagesMap = nil;
	} else {
		[self.tableView reloadData];
	}
}

- (void)unloadTableViewImages {
	// 打开return,对比分析
	//	return;
	if (_tableView) {
		NSArray *cells = [self.tableView visibleCells];
		self.displayIndexPaths = nil;
		self.displayImagesMap = nil;
		NSMutableArray *tmpDisplayIndexPaths = [NSMutableArray array];
		NSMutableDictionary *tmpDisplayImagesMap = [NSMutableDictionary dictionary];
		for (UITableViewCell *cell in cells) {
			NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
			[tmpDisplayIndexPaths addObject:indexPath];
			
			if (cell.imageView.image) {
				NSString *cacheKey = [NSString stringWithFormat:@"%ld_%ld", indexPath.section, indexPath.row];
				[tmpDisplayImagesMap setValue:cell.imageView.image forKey:cacheKey];
				cell.imageView.image = nil;
			}
		}
		self.displayIndexPaths = tmpDisplayIndexPaths.copy;
		self.displayImagesMap = tmpDisplayImagesMap.copy;
	}
}

- (void)applicationWillEnterForeground:(NSNotification *)notice {
	[self loadTableViewImages];
}

- (void)applicationDidEnterBackground:(NSNotification *)notice {
	self.reloadAnimationType = UITableViewRowAnimationNone;
	[self unloadTableViewImages];
}

// MARK: - lazy
- (UITableView *)tableView {
	if (!_tableView) {
		UITableView *tableView = UITableView.alloc.init;
		_tableView = tableView;
		tableView.frame = self.view.bounds;
		tableView.rowHeight = 375.0f;
		tableView.allowsSelection = NO;
		tableView.dataSource = self;
		tableView.delegate = self;
		[tableView registerClass:CustomTableViewCell.class
		  forCellReuseIdentifier:NSStringFromClass(self.class)];
	}
	return _tableView;
}

@end
